﻿using JsonRpcService.Contract;
using Microsoft.AspNetCore.Mvc;
using StreamJsonRpc;

namespace WebSocketSample.Server.Controllers;

public class RpcController(ILogger<RpcController> logger, IGreeterService greeter) : ControllerBase
{
    [Route("/rpc/greeter")]
    public async Task<IActionResult> Greeter()
    {
        if (!HttpContext.WebSockets.IsWebSocketRequest)
            return new BadRequestResult();

        logger.LogInformation("等待客户端连接...");
        var socket = await HttpContext.WebSockets.AcceptWebSocketAsync();
        logger.LogInformation("已与客户端建立连接");

        var handler = new WebSocketMessageHandler(socket);
        using (var jsonRpc = new JsonRpc(handler, greeter))
        {
            logger.LogInformation("开始监听客户端消息...");
            jsonRpc.StartListening();
            await jsonRpc.Completion;
            logger.LogInformation("客户端断开了连接");
        }

        return new EmptyResult();
    }
}
